import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { Component, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DValidateRules, DialogService, FormLayout, TableWidthConfig } from 'ng-devui';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { DataSharingService } from 'src/app/@core/services/dataSharing/data-sharing.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { MaterialService } from 'src/app/@core/services/material/material.service';
import { SalesService } from 'src/app/@core/services/sales/sales.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import { SelectCustomerComponent } from 'src/app/@shared/components/select-customer/select-customer.component';

import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';

import { SetDeliveryDateComponent } from '../../sales-order/set-delivery-date/set-delivery-date.component';
import { SaleOrder, SaleDeliver, SaleReturn } from 'src/app/@core/data/sale';
import { SelectInventoryComponent } from 'src/app/@shared/components/select-inventory/select-inventory.component';
import { SelectSalesInvoiceComponent } from './select-sales-invoice/select-sales-invoice.component';
import { environment } from 'src/environments/environment';
import { SelectStorehouseComponent } from 'src/app/@shared/components/select-storehouse/select-storehouse.component';
import { SelectPositionComponent } from 'src/app/@shared/components/select-position/select-position.component';


@Component({
  selector: 'app-sales-return-add',
  templateUrl: './sales-return-add.component.html',
  styleUrls: ['./sales-return-add.component.scss']
})
export class SalesReturnAddComponent {
  Math = Math;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  saleOrder = {
    saleOrderId: 0, // 销售订单ID
    Num: null, // 报价单号
    saleOrderNum: null, // 销售订单号
    orderDate: null, // 订单日期
    customerOrderNum: '', // 客户订单号
    customerName: '', // 客户名称
    deliveryDate: null, // 交货日期
    isAudit: false, // 是否审核
    isClosed: false, // 是否关闭
    partTotalQuantity: 0, // 零件总数量
    partShippedQuantity: 0, // 已发货数量
    partUnshippedQuantity: 0, // 未发货数量
    advancePaymentAmount: 0, // 预付款金额
    creationDate: null, // 创建日期
    creator: '', // 创建者
    orderType: '', // 订单类型
    company: '', // 公司
    customerShortName: '', // 客户简称
    customerContact: '', // 客户联系人
    contactInfo: '', // 联系信息
    salesman: '', // 销售员
    salesmanId: null, // 销售员
    department: '', // 部门
    departmentId: null, // 部门
    settlementCurrency: '', // 结算货币
    settlementMethod: '', // 结算方式
    paymentTerm: '', // 付款条件
    deliveryAddress: '', // 交货地址
    remark: '', // 备注
    totalQuantity: 0, // 总数量
    totalAmountWithTax: 0, // 含税总金额
    totalTaxAmount: 0, // 总税额
    totalDiscountAmountWithTax: 0, // 折扣后含税总金额
    totalDiscountTaxAmount: 0, // 折扣后总税额
    files: [], // 文件列表
    fileRemarks: [], // 文件备注
    saleOrderParts: [
      {
        saleOrderPartId: 0, // 零件ID
        saleOrderNum: '', // 销售订单号
        partId: 0, // 零件ID
        partNum: '', // 零件编号
        image: '', // 图片
        attachment: '', // 附件
        partName: '', // 零件名称
        partType: '', // 零件类型
        description: '', // 描述
        plannedShipmentDate: null, // 计划发货日期
        salesQuantity: 0, // 销售数量
        realTimeInventory: 0, // 实时库存
        saleReturnPartWarehouseId: 0,
        warehouseName: '',
        saleReturnPartPositionId: 0,
        sourceQuotationNum: null, // 来源报价单号
        quantity: 0, // 数量
        partUOM: '', // 单位
        priceWithTax: 0, // 含税价格
        priceWithoutTax: 0, // 不含税价格
        taxRate: 0, // 税率
        discount: 1, // 折扣
        discountPriceWithTax: 0, // 折扣后含税价格
        amountWithTax: 0, // 含税金额
        amountWithoutTax: 0, // 不含税金额
        taxAmount: 0, // 税额
        discountAmountWithTax: 0, // 折扣后含税金额
        discountAmountWithoutTax: 0, // 折扣后不含税金额
        discountTaxAmount: 0, // 折扣后税额
        partRemark: '', // 零件备注
        saleOrderId: 0, // 销售订单ID
        saleDeliverPartId: 0,
        returnedAmount: 0,
      }
    ],
    customerContactID: null,
    customerID: null
  }

  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px'
    },
    {
      field: '物料编码',
      width: '200px'
    },
    {
      field: '图片',
      width: '150px'
    },
    {
      field: '物料名称',
      width: '150px'
    },
    {
      field: '规格型号',
      width: '150px'
    },
    {
      field: '物料描述',
      width: '150px'
    },
    {
      field: '计划发货日期',
      width: '200px'
    },
    {
      field: '实时库存',
      width: '150px'
    },
    {
      field: '数量',
      width: '170px'
    },
    {
      field: '已退数量',
      width: '150px'
    },
    {
      field: '可退数量',
      width: '150px'
    },
    {
      field: '数量',
      width: '170px'
    },
    {
      field: '退货仓库',
      width: '170px'
    },
    {
      field: '退货库位',
      width: '170px'
    },
    {
      field: '单位',
      width: '150px'
    },
    {
      field: '单价(含税)',
      width: '170px'
    },
    {
      field: '单价（不含税）',
      width: '150px'
    },
    {
      field: '税率（%）',
      width: '170px'
    },
    {
      field: '折扣（%）',
      width: '150px'
    },
    {
      field: '折扣单价（含税）',
      width: '150px'
    },
    {
      field: '含税金额',
      width: '150px'
    },
    {
      field: '不含税金额',
      width: '150px'
    },
    {
      field: '税额',
      width: '150px'
    },
    {
      field: '折扣不含税金额',
      width: '150px'
    },
    {
      field: '折扣含税金额',
      width: '150px'
    },
    {
      field: '折扣税额',
      width: '150px'
    },
    {
      field: '备注',
      width: '150px'
    },
    {
      field: '来源报价单号',
      width: '150px'
    }
  ];
  dataTableOptions = {
    columns: [
      {
        field: 'name',
        header: '物料编码',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '图片',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料名称',
        fieldType: 'text',
      },

      {
        field: 'name',
        header: '规格型号',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '物料描述',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '退货日期',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '源单数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '已退数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '可退数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '退货数量',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '退货仓库',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '退货仓位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单位',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价(含税)',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '单价（不含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税率（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣（%）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣单价（含税）',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣不含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣含税金额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '折扣税额',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '备注',
        fieldType: 'text',
      },
      {
        field: 'name',
        header: '来源报价单号',
        fieldType: 'text',
      },
    ]
  }
  saleOrderRules: { [key: string]: DValidateRules } = {
    saleOrderNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*订单号不能为空' },
        { minlength: 2, message: '*订单号长度至少为2' },
        { maxlength: 40, message: '*订单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*订单号不能包含空格' }
      ]
    },
    customerName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*客户不能为空' },
      ]
    },
    orderDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*单据日期不能为空' },
      ]
    },
    partNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料不能为空' },
      ]
    },
    plannedShipmentDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*退货时间不能为空' },
      ]
    },
    deliveryDate: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*退货时间不能为空' },
      ]
    },
    priceWithTax: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*物料单价不能为空' },
      ]
    },
    quantity: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*数量不能为空' },
      ]
    },
    salesman: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*数量不能为空' },
      ]
    }
  }
  customerLinkMan: any = [];
  msgs: Array<Object> = [];
  customerContact: any = [];
  currencyOptions: any = [];
  settlementMethodOptions: any = [];
  data: any;
  loadData: boolean;
  collectionPeriods: any;
  defaultDate: any=null
  warehouseData: any;
  constructor(private DialogService: DialogService, private UserService: UserService, private CustomerService: CustomerService, private SalesService: SalesService,private router: Router, private EncodeRulesService: EncodeRulesService, private ReviewRolesService:ReviewRolesService) { }
  ngOnInit(): void {
    this.EncodeRulesService.GenerateWarehouseCodeRule('销售退货单','销售退货单').subscribe((data: any) => {
      this.saleOrder.saleOrderNum = data
    })
    this.CustomerService.GetPagedCurrency(1, 9999).subscribe((data: any) => {
      this.currencyOptions = data.items;
    })
    this.CustomerService.GetPagedSettlementMethodF({
      PageSize:9999,
      PageNumber:1,
    }).subscribe((data: any) => {
      this.settlementMethodOptions = data.items;
    })
    this.CustomerService.GetPagedCollectionPeriod({})
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.saleOrder.creator = JSON.parse(userinfoString).username;
    }
    this.CustomerService.GetPagedCollectionPeriod({
      PageSize: 999,
      PageNumber: 1,
      SearchStatus: '收款'
    }).subscribe((data: any) => {
      this.collectionPeriods = data.items
    })
    this.saleOrder.orderDate = new Date()
    this.defaultDate = this.saleOrder.orderDate
  }
  deliveryDate($event:any){
    this.defaultDate =$event
    this.saleOrder.saleOrderParts.map((item:any)=>{
      item.plannedShipmentDate = this.defaultDate
    })
  }
  addRow() {
    this.saleOrder.saleOrderParts.push({
      saleOrderPartId: 0,
      saleOrderNum: '',
      partNum: '',
      image: '',
      attachment: '',
      partName: '',
      partType: '',
      description: '',
      plannedShipmentDate: this.defaultDate,
      salesQuantity: 0,
      realTimeInventory: 0,
      sourceQuotationNum: null,
      saleReturnPartWarehouseId: 0,
      saleReturnPartPositionId: 0,
      quantity: 0,
      partUOM: '',
      priceWithTax: 0,
      priceWithoutTax: 0,
      taxRate: 0,
      discount: 1,
      discountPriceWithTax: 0,
      amountWithTax: 0,
      amountWithoutTax: 0,
      taxAmount: 0,
      discountAmountWithTax: 0,
      discountAmountWithoutTax: 0,
      discountTaxAmount: 0,
      partRemark: '',
      saleOrderId: 0,
      partId: 0,
      warehouseName: '',
      saleDeliverPartId: 0,
      returnedAmount: 0,
    });
  }//添加行
  addRowA(index:number,rowItem:any){
    const newRowItem = {...rowItem};
    this.saleOrder.saleOrderParts.splice(index+1,0,newRowItem);
    this.saleOrder.saleOrderParts[index+1].quantity = 0;
  }
  deleteRow(index: number) {
    this.saleOrder.saleOrderParts.splice(index, 1);
    this.calculateTotal()
    if (this.saleOrder.saleOrderParts.length == 0) {
      this.addRow();
    }
  }//删除行
  taxRateChange(rowitem: any, value: number) {
    rowitem.taxRate = value / 100;
    this.calculateAmount(rowitem);
    this.calculateTotal();
  }//税率改变
  quantityChange(rowitem: any) {
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//数量改变
  priceWithTaxChange(rowitem: any) {
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//含税单价改变
  discountChange(rowitem: any, value: number) {
    rowitem.discount = value / 100;
    this.calculateAmount(rowitem)
    this.calculateTotal()
  }//折扣改变
  calculateAmount(item: any): void {
    item.priceWithoutTax = +(item.priceWithTax / (1 + item.taxRate)).toFixed(4);
    item.amountWithTax = +(item.priceWithTax *item.quantity).toFixed(4);
    item.taxAmount = +((item.priceWithTax - item.priceWithoutTax)*item.quantity).toFixed(4);
    item.amountWithoutTax = +(item.amountWithTax - item.taxAmount).toFixed(4);
    item.discountPriceWithTax = +(item.priceWithTax * item.discount).toFixed(4);
    item.discountAmountWithoutTax = +(item.amountWithoutTax * item.discount).toFixed(4);
    item.discountTaxAmount = +(item.taxAmount * item.discount).toFixed(4);
    item.discountAmountWithTax = +(item.discountPriceWithTax*item.quantity).toFixed(4);
  }
  calculateTotal() {
    this.saleOrder.totalQuantity = this.saleOrder.saleOrderParts.reduce((prev, cur) => prev + cur.quantity, 0);
    this.saleOrder.totalAmountWithTax = this.saleOrder.saleOrderParts.reduce((prev, cur) => prev + cur.amountWithTax, 0);
    this.saleOrder.totalTaxAmount = this.saleOrder.saleOrderParts.reduce((prev, cur) => prev + cur.taxAmount, 0);
    this.saleOrder.totalDiscountAmountWithTax = this.saleOrder.saleOrderParts.reduce((prev, cur) => prev + cur.discountAmountWithTax, 0);
    this.saleOrder.totalDiscountTaxAmount = this.saleOrder.saleOrderParts.reduce((prev, cur) => prev + cur.discountTaxAmount, 0);
  }//计算总金额
  isStartApproval: boolean = false
  isStartApprovalChange() {
    this.isStartApproval = true
  }
  submit($event: any) {
    if ($event.valid) {
      this.saleOrder.creationDate = new Date()
      this.saleOrder.saleOrderParts.forEach((item: any) => {
        item.saleOrderNum = this.saleOrder.saleOrderNum
      });
      const SaleReturn:SaleReturn ={
        orderDate: this.saleOrder.orderDate, // 订单日期
        saleReturnNum: this.saleOrder.saleOrderNum, // 销售退货单号
        saleReturnCustomerId: this.saleOrder.customerID, // 客户ID
        company: this.saleOrder.company, // 公司
        chineseName: this.saleOrder.customerName, // 客户中文名
        customerAbbreviation: this.saleOrder.customerShortName, // 客户简称
        customerContactName: this.saleOrder.customerContact, // 客户联系人姓名
        customerContactPhone: this.saleOrder.contactInfo, // 客户联系人电话
        saleReturnSalesmanId: this.saleOrder.salesmanId, // 销售员ID
        salesmanName: this.saleOrder.salesman, // 销售员姓名
        saleReturnDepartmentId: this.saleOrder.departmentId, // 部门ID
        departmentName: this.saleOrder.department, // 部门名称
        scheduledReturnTime: this.saleOrder.deliveryDate, // 计划退货时间
        returnType: this.saleOrder.orderType, // 退货类型
        currencyName: this.saleOrder.settlementCurrency, // 结算货币
        settlementMethodName: this.saleOrder.settlementMethod, // 结算方式
        isWriteOff: false, // 是否核销
        note: this.saleOrder.remark, // 备注
        status: '未开始审核', // 是否推送
        isReturn: false, // 是否退货
        isReceive: false, // 是否接收
        isCancellation: false, // 是否取消
        isPrint: false, // 是否打印
        createTime: this.saleOrder.creationDate, // 创建时间
        createUser: this.saleOrder.creator, // 创建人
        returnedAmount: 0, // 已退货数量
        unReturnedAmount: this.saleOrder.totalQuantity, // 未退货数量
        returnAmount: this.saleOrder.totalQuantity, // 退货数量
        taxAmount: this.saleOrder.totalAmountWithTax, // 含税金额
        tax: this.saleOrder.totalTaxAmount, // 税额
        unTaxAmount: this.saleOrder.totalAmountWithTax - this.saleOrder.totalTaxAmount, // 不含税金额
        taxDiscountAmount: this.saleOrder.totalDiscountAmountWithTax, // 含税折扣金额
        taxDiscount: this.saleOrder.totalDiscountTaxAmount, // 含税折扣税额
        discountAmount: this.saleOrder.totalDiscountAmountWithTax - this.saleOrder.totalDiscountTaxAmount, // 不含税折扣金额
        file: [], // 文件
        fileNote: [], // 文件备注
        saleReturnParts: this.saleOrder.saleOrderParts.map((item: any) => ({
          saleReturnPartPartId: item.partId, // 零件ID
          partNum: item.partNum, // 零件编号
          partName: item.partName, // 零件名称
          scheduledReturnTime: item.plannedShipmentDate, // 计划退货时间
          scheduledReturnAmount: item.quantity, // 计划退货数量
          returnedAmount: item.returnedAmount, // 已退货数量
          returningAmount: 0, // 正在退货数量
          saleReturnPartWarehouseId: item.saleDeliverPartWarehouseId, // 仓库ID
          warehouseName: item.saleDeliverPartWarehouseName, // 仓库名称
          saleReturnPartPositionId: item.saleDeliverPartPositionId, // 库位ID
          positionName: item.saleDeliverPartPositionName, // 库位名称
          priceWithTax: item.priceWithTax, // 含税价格
          priceWithoutTax: item.priceWithoutTax, // 不含税价格
          taxRate: item.taxRate, // 税率
          discount: item.discount, // 折扣
          discountPriceWithTax: item.discountPriceWithTax, // 含税折扣价格
          amountWithTax: item.amountWithTax, // 含税金额
          amountWithoutTax: item.amountWithoutTax, // 不含税金额
          taxAmount: item.taxAmount, // 税额
          discountAmountWithTax: item.discountAmountWithTax, // 含税折扣金额
          discountAmountWithoutTax: item.discountAmountWithoutTax, // 不含税折扣金额
          discountTaxAmount: item.discountTaxAmount, // 含税折扣税额
          note: item.partRemark, // 备注
          saleOrderNum: item.saleOrderNum, // 销售订单号
          saleDeliverNum: item.sourceQuotationNum, // 销售交货单号
          saleDeliverPartId: item.saleDeliverPartId, // 销售交货单零件ID
          partType: item.partType, // 零件类型
          partUOM: item.partUOM, // 零件单位
          image: item.image, // 图片
          description: item.description, // 描述
        }))
      }
      this.SalesService.CreateSaleReturn(SaleReturn).subscribe((data: any) => {
        if(this.isStartApproval){
          this.ReviewRolesService.StartApprovalFlow('销售退货单审核流配置',[SaleReturn.saleReturnNum]).subscribe((data: any) => {
            this.showToast('success', '成功', '新增成功')
            setTimeout(() => {
              this.router.navigate(['/pages/sales-master/sales-return-order'])
            }, 1000);
          },(error:any)=>{
            this.showToast('error', '错误','单据创建成功，流程启动失败');
            setTimeout(() => {
              this.router.navigate(['/pages/sales-master/sales-return-order'])
            }, 1000 );
          }
        )
        }else{
          this.showToast('success', '成功', '新增成功')
        setTimeout(() => {
          this.router.navigate(['/pages/sales-master/sales-return-order'])
        }, 1000);
        }
      },
      (error: any) => {
        if (error.status === 404) {
          this.showToast('error', '错误', '网络连接错误');
        } else {
          this.showToast('error', '错误', error.error);
        }
      }
      )
    }else {
      this.showToast('warn', '错误', '请填写必填项')
    }
  }//提交
  selectCustomer(dialogtype?: string,reset?:boolean) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: "",
      title: '选择客户',
      content: SelectCustomerComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {

            this.saleOrder.customerName = results.modalContentInstance.selectData.chineseName;
            this.saleOrder.customerID = results.modalContentInstance.selectData.customerId;
            this.saleOrder.customerShortName = results.modalContentInstance.selectData.customerAbbreviation;
            this.customerLinkMan = results.modalContentInstance.selectData.customerContacts;
            this.saleOrder.settlementCurrency = results.modalContentInstance.selectData.customerCurrencyName;
            this.saleOrder.salesmanId = results.modalContentInstance.selectData.salesmanId;
            this.saleOrder.settlementMethod = results.modalContentInstance.selectData.customerSettlementMethodName;
            this.saleOrder.paymentTerm = results.modalContentInstance.selectData.customerCollectionPeriodName;
            this.saleOrder.deliveryAddress = results.modalContentInstance.selectData.invoiceAddress;
            if (results.modalContentInstance.selectData.customerContacts.length > 0) {
              this.saleOrder.customerContact = results.modalContentInstance.selectData.customerContacts[0].customerContactName;
              this.saleOrder.contactInfo = results.modalContentInstance.selectData.customerContacts[0].phone;
              this.saleOrder.customerContactID = results.modalContentInstance.selectData.customerContacts[0].customerContactId;
              this.customerContact = { customerContactId: results.modalContentInstance.selectData.customerContacts[0].customerContactId, customerContactName: results.modalContentInstance.selectData.customerContacts[0].customerContactName }
            }
            this.UserService.GetUserById(results.modalContentInstance.selectData.salesmanId).subscribe((data: any) => {
              this.saleOrder.salesman = data.name;
              this.saleOrder.departmentId = data.departmentId;
              this.UserService.GetDepartmentById(data.departmentId).subscribe((data: any) => {
                this.saleOrder.department = data.name;
              })
            })
            if(reset){
              this.saleOrder.saleOrderParts = [
                {
                  saleOrderPartId: 0,
                  saleOrderNum: '',
                  partId: 0,
                  partNum: '',
                  image: '',
                  attachment: '',
                  partName: '',
                  partType: '',
                  description: '',
                  plannedShipmentDate: null,
                  salesQuantity: 0,
                  realTimeInventory: 0,
                  saleReturnPartWarehouseId: 0,
                  warehouseName: '',
                  saleReturnPartPositionId: 0,
                  sourceQuotationNum: null,
                  quantity: 0,
                  partUOM: '',
                  priceWithTax: 0,
                  priceWithoutTax: 0,
                  taxRate: 0,
                  discount: 0,
                  discountPriceWithTax: 0,
                  amountWithTax: 0,
                  amountWithoutTax: 0,
                  taxAmount: 0,
                  discountAmountWithTax: 0,
                  discountAmountWithoutTax: 0,
                  discountTaxAmount: 0,
                  partRemark: '',
                  saleOrderId: 0,
                  saleDeliverPartId: 0,
                  returnedAmount: 0
                }
              ]
              this.calculateAmount(this.saleOrder.saleOrderParts[0])
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectCustomerBefore(dialogtype?: string) {
    if(this.saleOrder.saleOrderParts[0].partNum&&this.saleOrder.customerID){
      const results = this.DialogService.open({
        id: 'dialog-service',
        maxHeight: '400px',
        width: '300px',
        backdropCloseable: true,
        data: "",
        title: '',
        dialogtype: dialogtype,
        html: true,
        content: '<div style="color:#8a6d3b;font-size: 14px;">确定切换客户，这将会使您构建的物料行数据重置！</div>',
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              results.modalInstance.hide();
              this.selectCustomer(null,true)
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }else{
      this.selectCustomer(null,true)
    }
  }
  selectUser(dialogtype?: string) {
    if (this.saleOrder.customerName != "") {
      const results = this.DialogService.open({
        id: 'Add',
        maxHeight: '400px',
        width: '800px',
        backdropCloseable: true,
        data: "",
        title: '选择业务员',
        content: SelectUserComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {

              this.saleOrder.salesman = results.modalContentInstance.selectData.name;
              this.saleOrder.salesmanId = results.modalContentInstance.selectData.id;
              this.saleOrder.departmentId = results.modalContentInstance.selectData.departmentId;
              this.UserService.GetDepartmentById(results.modalContentInstance.selectData.departmentId).subscribe((data: any) => {
                this.saleOrder.department = data.name;
              })
              results.modalInstance.hide();
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    } else {
      this.showToast('error', '错误', '请先选择客户')
    }

  }
  slectLinkMan(event: any) {
    this.CustomerService.GetCustomerContactById(event.customerContactId).subscribe((data: any) => {

      this.saleOrder.customerContact = data.customerContactName
      this.saleOrder.customerContactID = data.customerContactId
      this.saleOrder.contactInfo = data.phone
    })
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map(url => environment.modifiedApiUrl + url);
    return urls;
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  setDeliveryDate(dialogtype?: string) {
    let data = {
      display: false
    };
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '400px',
      backdropCloseable: true,
      data: data,
      title: '选择退货日期',
      content: SetDeliveryDateComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.form.plannedShipmentDate) {
              this.saleOrder.saleOrderParts.forEach((item) => {
                item.plannedShipmentDate = results.modalContentInstance.form.plannedShipmentDate;
                results.modalInstance.hide();

              })
            } else {
              data.display = true;
            }
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  cancel() {
    this.router.navigate(['/pages/sales-master/sales-return-order'])
  }
  selectOrder(dialogtype?: string) {
    const saleDeliverPartIds = this.saleOrder.saleOrderParts.map(
      (item:any)=>{
        return item.saleDeliverPartId
      }
    )
    const customerName = this.saleOrder.customerName
    const results = this.DialogService.open({
      id: 'Add',
      width: '1250px',
      backdropCloseable: true,
      title: '选择销售发货单',
      data:{
        saleDeliverPartIds:saleDeliverPartIds,
        customerName:customerName
      },
      content: SelectSalesInvoiceComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.filterRows) {
              if(this.checkCustomerIDs(results.modalContentInstance.filterRows)){
                if (results.modalContentInstance.filterRows.length > 1) {
                  this.CustomerService.GetCustomerById(results.modalContentInstance.filterRows[0].saleDeliverCustomerId).subscribe((data: any) => {
                    this.saleOrder.customerID = data.customerId
                    this.customerLinkMan = data.customerContacts
                    this.saleOrder.customerName = data.chineseName
                    this.saleOrder.customerShortName = data.customerAbbreviation
                    this.saleOrder.settlementCurrency = data.customerCurrencyName
                    this.saleOrder.settlementMethod = data.customerSettlementMethodName
                    this.saleOrder.paymentTerm = data.customerCollectionPeriodName
                    this.saleOrder.deliveryAddress = data.invoiceAddress
                    this.saleOrder.customerContact = data.customerContacts[0].customerContactName
                    this.saleOrder.contactInfo = data.customerContacts[0].phone
                    this.saleOrder.customerContactID = data.customerContacts[0].customerContactId
                    this.customerContact = { customerContactId: data.customerContacts[0].customerContactId, customerContactName: data.customerContacts[0].customerContactName }
                    this.UserService.GetUserById(data.salesmanId).subscribe((data: any) => {
                      this.saleOrder.salesman = data.name
                      this.saleOrder.salesmanId = data.id
                      this.saleOrder.departmentId = data.departmentId
                      this.UserService.GetDepartmentById(data.departmentId).subscribe((data: any) => {
                        this.saleOrder.department = data.name
                      })
                    })
                  })
                }else{
                  this.CustomerService.GetCustomerById(results.modalContentInstance.filterRows[0].saleDeliverCustomerId).subscribe((data: any) => {
                    this.saleOrder.customerID = data.customerId
                    this.saleOrder.customerName = data.chineseName
                    this.customerLinkMan = data.customerContacts
                    this.saleOrder.customerShortName = data.customerAbbreviation
                  })
                  this.SalesService.GetSaleDeliverById(results.modalContentInstance.filterRows[0].saleDeliverPartSaleDeliverId).subscribe((data: any) => {
                    this.saleOrder.salesman = data.salesmanName
                    this.saleOrder.customerShortName = data.customerAbbreviation
                    this.saleOrder.settlementCurrency = data.currencyName
                    this.saleOrder.settlementMethod = data.settlementMethodName
                    this.saleOrder.paymentTerm = data.collectionPeriodName
                    this.saleOrder.deliveryAddress = data.deliveryAddress
                    this.saleOrder.customerContact = data.customerContactName
                    this.saleOrder.contactInfo = data.customerContactPhone
                    this.saleOrder.department = data.departmentName
                    this.saleOrder.remark = data.note
                  })
                }
                this.saleOrder.saleOrderParts = this.saleOrder.saleOrderParts.filter(part => part.partNum!==""&&part.partNum!==null)
                const saleOrderParts  = results.modalContentInstance.filterRows.map((item: any) => ({
                  partNum: item.partNum,
                  image: item.fileURL,
                  partName: item.partName,
                  partType: item.partType,
                  description: item.description,
                  partUOM: item.partUOM,
                  priceWithTax: item.priceWithTax,
                  priceWithoutTax: 0,
                  scheduledDeliverAmount: item.scheduledDeliverAmount,
                  realTimeInventory: 0,
                  quantity: item.scheduledDeliverAmount-item.returnedAmount,
                  taxRate: item.taxRate,
                  discount: item.discount,
                  discountPriceWithTax: 0,
                  amountWithTax: 0,
                  amountWithoutTax: 0,
                  taxAmount: 0,
                  returnedAmount: item.returnedAmount,
                  discountAmountWithTax: 0,
                  discountAmountWithoutTax: 0,
                  discountTaxAmount: 0,
                  partRemark: item.note,
                  saleOrderNum: item.saleOrderNum,
                  saleDeliverPartWarehouseName: item.warehouseName,
                  saleDeliverPartPositionName: item.positionName,
                  saleDeliverPartWarehouseId: item.saleDeliverPartWarehouseId,
                  saleDeliverPartPositionId: item.saleDeliverPartPositionId,
                  sourceQuotationNum: item.saleDeliverNum,
                  saleOrderId: item.saleDeliverPartSaleDeliverId,
                  partId: item.saleDeliverPartPartId,
                  saleDeliverPartId:item.saleDeliverPartId
                }));
                this.saleOrder.saleOrderParts = this.saleOrder.saleOrderParts.concat(saleOrderParts);
                this.saleOrder.saleOrderParts.forEach(part => this.calculateAmount(part));
                this.calculateTotal();
                results.modalInstance.hide();
              }else{
                this.showToast('error', '错误', '请选择同一客户的销售发货单')
              }
            }
            results.modalInstance.hide();
          }
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ]
    })
  }
  SelectStorehouse(rowItem:any,dialogtype?:string){
    if(rowItem.partNum==""){
      this.showToast('error', '错误', '请先选择物料')
      return
    }
    const results = this.DialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width:'1000px',
      title: '选择仓库',
      data:rowItem,
      content: SelectStorehouseComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){

               rowItem.saleReturnPartWarehouseId=results.modalContentInstance.selectData.warehouseId;
                rowItem.saleDeliverPartWarehouseName =results.modalContentInstance.selectData.warehouseName;
                rowItem.saleReturnPartPositionId =null
                rowItem.saleDeliverPartPositionName =null
                this.warehouseData = results.modalContentInstance.selectData
              results.modalInstance.hide();
              }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectPosition(rowItem:any,dialogtype?:string){
    if(rowItem.warehouseId==0){

      return
    }
    let data = {
      display: false,
      warehouseData: this.warehouseData,
      warehouseId: rowItem.warehouseId,
      placeholder: '请选择库位'
    };
    const results = this.DialogService.open({
      id: 'dialog-service',
      showAnimation: true,
      width:'1000px',
      data:data,
      title: '选择仓位',
      content: SelectPositionComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'primary',
          text: '确定',
          disabled: false,
          handler: ($event: Event) => {
            if(results.modalContentInstance.selectData){
              rowItem.saleDeliverPartPositionName = results.modalContentInstance.selectData.positionName;
              rowItem.saleReturnPartPositionId = results.modalContentInstance.selectData.positionId;
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  checkCustomerIDs(customerRows:any) {
    // 如果数组长度为1或为空，直接返回true
    if (customerRows.length <= 1) {
      return true;
    }
    // 获取第一个元素的customerID
    const firstCustomerID = customerRows[0].saleDeliverCustomerId;
    // 检查数组中每个元素的customerID是否都与第一个元素的customerID相同
    return customerRows.every((row: any) => row.saleDeliverCustomerId === firstCustomerID);
  }
}
